var express     = require('express')
  , cluster		= require('cluster')
  , flash       = require('connect-flash')
  , envConfig   = require('config')
  , poolModule  = require('generic-pool')
  , winston     = require('winston')
  , routes      = require('./routes')
  , admin       = require('./routes/admin')
  , customer    = require('./routes/customer')
  , cservice    = require('./routes/cservice')
  , driver      = require('./routes/driver')
  , orderform	= require('./routes/orderform');

//获得系统CPU数量
var numCPUs = require('os').cpus().length;

//加载配置信息
var CFG_SERVER  	= envConfig.server,
	CFG_DB_MYSQL    = envConfig.dbMysql,
	CFG_STORE_REDIS = envConfig.storeRedis;

//加载配置信息
var defs        = require('./utils/defs'),
	port        = process.env.PORT  || CFG_SERVER.port,
	forks       = process.env.FORKS || CFG_SERVER.forks;

//定义打印日志方式及格式
var logmessage  = function(message) {
    message = '#' + (process.env.NODE_WORKER_ID ? process.env.NODE_WORKER_ID : 'M') + ': ' + message;
    if (winston) {
        winston.log('info', message);
    } else {
        console.log(message);
    }
};

//mysql连接池
var mysqlPool = poolModule.Pool({
    name     : 'mysql',
    create   : function(callback) {
    	 var mysqlConfig = {
             host: CFG_DB_MYSQL.host,
             port: CFG_DB_MYSQL.port,
             user: CFG_DB_MYSQL.username,
             password: CFG_DB_MYSQL.password,
             database: CFG_DB_MYSQL.dbname
         };
         var mysqlClient = require('mysql').createConnection(mysqlConfig);
         mysqlClient.connect();
         callback(null,mysqlClient);
    },
    destroy  : function(client) { client.end(); },
    max      : 300,
    min      : 2, 
    idleTimeoutMillis : 30000,
    log : true 
});

//redis连接池
var redisPool = poolModule.Pool({
    name     : 'redis',
    create   : function(callback) {
        var client = require('redis').createClient();  
        callback(null, client);
    },
    destroy  : function(client) { client.quit(); }, //当超时则释放连接
    max      : 300,   //最大连接数
    idleTimeoutMillis : 30000,  //超时时间
    log : true,  
});

//初始化APP
var app = express();
//设置端口
app.set('port', port);
//设置view
app.set('views', __dirname + '/views');
//设置页面模版
app.set('view engine', 'ejs');
app.use(express.favicon());
//Connect內建的middleware，设置此处可以将client提交过来的post请求放入request.body中
app.use(express.bodyParser({uploadDir:'./public/temp'}));
//Connect內建的，可以协助处理POST请求伪装PUT、DELETE和其他HTTP methods。
app.use(express.methodOverride());
//设置cookies加密钥
app.use(express.cookieParser());
//设置session
app.use(express.session({secret:'mySecret'}));
//设置flash缓存，重定向变量传递
app.use(flash());
//使用路由
app.use(app.router);
//设置配置文件
app.envConfig = envConfig;
app.defs = defs;
app.logmessage = logmessage;
app.mysqlClient = mysqlPool;
app.redisClient = redisPool;

app.configure('development', function(){
    app.use(express.static(__dirname + '/public'));
    app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  var oneYear = 31557600000;
  app.use(express.static(__dirname + '/public', { maxAge: oneYear }));
  app.use(express.errorHandler());
  //500错误
  app.use(function(err, req, res, next) {
      res.render('500.ejs', {status: 500 });
  });
});

//路由
routes(app);
admin(app);
cservice(app);
customer(app);
driver(app);
orderform(app);


//if (cluster.isMaster) {
//  for (var i = 0; i < numCPUs; i++) {
//    cluster.fork();
//  }
//  cluster.on('exit', function(worker, code, signal) {
//    console.log('worker ' + worker.process.pid + ' died');
//  });
//} else {
		var server = require('http').createServer(app);
		require('./server').create(app,server);
		server.listen(port,function() {
	        app.logmessage('Listening on :' + port + ' in "' + app.settings.env + '" mode...');
	        return 0;
	    });
//}

